package com.oocl.ha.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

import com.oocl.ha.dao.UserDao;
import com.oocl.ha.entity.User;

@Repository("userDao")

public class UserDaoImpl implements UserDao {

	@PersistenceContext(name = "un")
	private EntityManager em;

	public User findUser(String account) {
		String sql = "select u from User u where u.account=:account";
		
		@SuppressWarnings("unchecked")
		List<User> user = em.createQuery(sql).setParameter("account", account).getResultList();
		if (user.isEmpty()) {
			return null;
		}else{
			return user.get(0);
		}
	}

	public int addUser(User user) {
		try {
			em.persist(user);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public User findById(int uid) {
		User user = em.find(User.class, uid);
		return user;
	}

	public int updateAddress(String account, String address) {
		String sql = "select u from User u where u.account=:account";
		try {
			@SuppressWarnings("unchecked")
			List<User> user = em.createQuery(sql).setParameter("account", account).getResultList();
			user.get(0).setAddress(address);
			em.persist(user.get(0));
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public int updatePassword(String account, String password) {
		String sql = "select u from User u where u.account=:account";
		try {
			@SuppressWarnings("unchecked")
			List<User> user = em.createQuery(sql).setParameter("account", account).getResultList();
			user.get(0).setPassword(password);
			em.persist(user.get(0));
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}


}
